/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.app.service;

import com.sun.jersey.server.impl.container.servlet.JerseyServletContainerInitializer;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.ejb.Stateless;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import org.codehaus.jettison.json.JSONArray;

/**
 *
 * @author Santiago
 */
@Stateless
@Produces(MediaType.APPLICATION_JSON)
@Path("/api")
public class AutocomplteTagsServices {

  @GET
  public String obtenerTags(@QueryParam("q") String q) {
    List<String> lsTags = new LinkedList<String>();
    JSONArray mJSONArray = new JSONArray();
    try {
      Class.forName("org.postgresql.Driver");
      Connection conn = DriverManager.getConnection(
              "jdbc:postgresql://localhost:5432/J_MICRO_BLOGGER", "postgres",
              "password");
      Statement stmt = conn.createStatement();
      String query = "select DISTINCT tag_name from jmb_post_tags where tag_name LIKE " + "'%" + q + "%' ";
      
      ResultSet rs = stmt.executeQuery(query);
      while (rs.next()) {
        String field = rs.getString("tag_name");
        lsTags.add(field);
        
      }
      mJSONArray = new JSONArray(lsTags);

    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return mJSONArray.toString();
  }
}
